<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\utils;


use app\madmin\model\Configuration;
use app\madmin\model\PayMode;
use app\Request;
use app\shop_admin\service\PicService;
use app\utils\weixin\WxBizMsgCrypt;
use think\facade\Cache;
use think\facade\Db;

class Weixin
{
    public $config;

    public function __construct($mall_id = 0)
    {
        $config = Db::table('jiecheng_configuration')
            ->where('type', 'WeixinApp')
            ->where('mall_id', $mall_id)
            ->value('configuration');
        $this->config = json_decode($config, true);

    }

    public function component_verify_ticket()
    {

        $timeStamp = request()->get('timestamp');
        $nonce = request()->get('nonce');
        $encrypt_type = request()->get('encrypt_type');
        $msg_sign = request()->get('msg_signature');
        $encryptMsg = file_get_contents('php://input');

        $token = $this->config['token'] ?? '';
        $encodingAesKey = $this->config['encodingAesKey'] ?? '';
        $appId = $this->config['appid'] ?? '';

        $pc = new Weixin1($token, $encodingAesKey, $appId);
        $msg = $pc->aesDecode($msg_sign, $timeStamp, $nonce, $encryptMsg);

        if ($msg) {
            $xml = new \DOMDocument();
            $xml->loadXML($msg);
            $array_e = $xml->getElementsByTagName('ComponentVerifyTicket');
            $component_verify_ticket = $array_e->item(0)->nodeValue;
            $wechat_verifyticket = array(
                'component_verify_ticket' => $component_verify_ticket,
                'uptime' => time());
            #"1小时50分失效"
            Cache::set('wechat_verifyticket:'.$appId, $wechat_verifyticket, 60 * 60 + 60 * 50);
            return true;
        } else {
            return false;
        }
    }
}